home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / PDOCUMENTTEMPLATE.PY < prev    next >
Encoding:
Python Source  |  2000-06-19  |  9.9 KB  |  297 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64. __doc__='''Python implementations of document template some features
  65.  
  66.  
  67. $Id: pDocumentTemplate.py,v 1.23.38.2 2000/06/19 14:26:51 shane Exp $'''
  68. __version__='$Revision: 1.23.38.2 $'[11:-2]
  69.  
  70. import string, sys, types
  71. from string import join
  72.  
  73. StringType=type('')
  74. TupleType=type(())
  75. isFunctionType={}
  76. for name in ['BuiltinFunctionType', 'BuiltinMethodType', 'ClassType',
  77.              'FunctionType', 'LambdaType', 'MethodType', 'UnboundMethodType']:
  78.     try: isFunctionType[getattr(types,name)]=1
  79.     except: pass
  80.  
  81. try: # Add function and method types from Extension Classes
  82.     import ExtensionClass
  83.     isFunctionType[ExtensionClass.PythonMethodType]=1
  84.     isFunctionType[ExtensionClass.ExtensionMethodType]=1
  85. except: pass
  86.  
  87. isFunctionType=isFunctionType.has_key
  88.  
  89. isSimpleType={}
  90. for n in dir(types):
  91.     if (n[-4:]=='Type' and n != 'InstanceType' and
  92.         not isFunctionType(getattr(types, n))):
  93.         isSimpleType[getattr(types, n)]=1
  94.  
  95. isSimpleType=isSimpleType.has_key
  96.  
  97. class InstanceDict:
  98.  
  99.     validate=None
  100.  
  101.     def __init__(self,o,namespace,validate=None):
  102.         self.self=o
  103.         self.cache={}
  104.         self.namespace=namespace
  105.         if validate is None: self.validate=namespace.validate
  106.         else: self.validate=validate
  107.  
  108.     def has_key(self,key):
  109.         return hasattr(self.self,key)
  110.  
  111.     def keys(self):
  112.         return self.self.__dict__.keys()
  113.  
  114.     def __repr__(self): return 'InstanceDict(%s)' % str(self.self)
  115.  
  116.     def __getitem__(self,key):
  117.  
  118.         cache=self.cache
  119.         if cache.has_key(key): return cache[key]
  120.         
  121.         inst=self.self
  122.  
  123.         if key[:1]=='_':
  124.             if key != '__str__':
  125.                 raise KeyError, key # Don't divuldge private data
  126.             r=str(inst)
  127.         else:
  128.             try: r=getattr(inst,key)
  129.             except AttributeError: raise KeyError, key
  130.  
  131.         v=self.validate
  132.         if v is not None: v(inst,inst,key,r,self.namespace)
  133.  
  134.         self.cache[key]=r
  135.         return r
  136.  
  137. class MultiMapping:
  138.  
  139.     def __init__(self): self.dicts=[]
  140.  
  141.     def __getitem__(self, key):
  142.         for d in self.dicts:
  143.             try: return d[key]
  144.             except KeyError, AttributeError: pass
  145.         raise KeyError, key
  146.  
  147.     def push(self,d): self.dicts.insert(0,d)
  148.  
  149.     def pop(self,n=1): del self.dicts[:n]
  150.  
  151.     def keys(self):
  152.         kz = []
  153.         for d in self.dicts:
  154.             kz = kz + d.keys()
  155.         return kz
  156.  
  157. class DictInstance:
  158.     
  159.     def __init__(self, mapping):
  160.         self.__d=mapping
  161.  
  162.     def __getattr__(self, name):
  163.         try: return self.__d[name]
  164.         except KeyError: raise AttributeError, name
  165.         
  166. class TemplateDict:
  167.  
  168.     level=0
  169.  
  170.     def _pop(self, n=1): return self.dicts.pop(n)
  171.     def _push(self, d): return self.dicts.push(d)
  172.  
  173.     def __init__(self):
  174.         m=self.dicts=MultiMapping()
  175.         self._pop=m.pop
  176.         self._push=m.push
  177.         try: self.keys=m.keys
  178.         except: pass
  179.  
  180.     def __getitem__(self,key,call=1,
  181.                     simple=isSimpleType,
  182.                     isFunctionType=isFunctionType,
  183.                     ):
  184.  
  185.         v=self.dicts[key]
  186.         if call and not simple(type(v)):
  187.             if hasattr(v,'isDocTemp') and v.isDocTemp: return v(None, self)
  188.             elif isFunctionType(type(v)): return v()
  189.             else:
  190.                 try: return v()
  191.                 except AttributeError, ev:
  192.                     try:
  193.                         tb=sys.exc_traceback
  194.                         if hasattr(sys, 'exc_info'): tb=sys.exc_info()[2]
  195.                         if hasattr(v,'__call__'):
  196.                             raise AttributeError, ev, tb
  197.                     finally: tb=None
  198.                 except TypeError: pass
  199.                         
  200.         return v
  201.  
  202.     def has_key(self,key):
  203.         try:
  204.             v=self.dicts[key]
  205.         except KeyError:
  206.             return 0
  207.         return 1
  208.     
  209.     getitem=__getitem__
  210.  
  211.     def __call__(self, *args, **kw):
  212.         if args:
  213.             if len(args)==1 and not kw:
  214.                 m=args[0]
  215.             else:
  216.                 m=self.__class__()
  217.                 for a in args: m._push(a)
  218.                 if kw: m._push(kw)
  219.         else: m=kw
  220.         return (DictInstance(m),)
  221.  
  222. def render_blocks(blocks, md):
  223.     rendered = []
  224.     append=rendered.append
  225.     for section in blocks:
  226.         if type(section) is TupleType:
  227.             l=len(section)
  228.             if l==1:
  229.                 # Simple var
  230.                 section=section[0]
  231.                 if type(section) is StringType: section=md[section]
  232.                 else: section=section(md)
  233.                 section=str(section)
  234.             else:
  235.                 # if
  236.                 cache={}
  237.                 md._push(cache)
  238.                 try:
  239.                     i=0
  240.                     m=l-1
  241.                     while i < m:
  242.                         cond=section[i]
  243.                         if type(cond) is StringType:
  244.                             n=cond
  245.                             try:
  246.                                 cond=md[cond]
  247.                                 cache[n]=cond
  248.                             except KeyError, v:
  249.                                 v=str(v)
  250.                                 if n != v: raise KeyError, v, sys.exc_traceback
  251.                                 cond=None
  252.                         else: cond=cond(md)
  253.                         if cond:
  254.                             section=section[i+1]
  255.                             if section: section=render_blocks(section,md)
  256.                             else: section=''
  257.                             m=0
  258.                             break
  259.                         i=i+2
  260.                     if m:
  261.                         if i==m: section=render_blocks(section[i],md)
  262.                         else: section=''
  263.  
  264.                 finally: md._pop()
  265.  
  266.         elif type(section) is not StringType:
  267.             section=section(md)
  268.  
  269.         if section: rendered.append(section)
  270.  
  271.     l=len(rendered)
  272.     if l==0: return ''
  273.     elif l==1: return rendered[0]
  274.     return join(rendered, '')
  275.     return rendered
  276.